let util = {};
let { config } = require('ws/ws-config.js');
// let config = wx.getExtConfigSync && JSON.stringify(wx.getExtConfigSync()) !== '{}' ? wx.getExtConfigSync() : require('../../config.js');

/**
 * @param controller, action, do，格式为 'wxapp/home/navs'
 * @param querystring 格式为 {参数名1 : 值1, 参数名2 : 值2}
 * @param {string} module - 模块名
*/
util.url = function (action, querystring, module) {
  let app = getApp();
  // app取值优先，fixed by roy
  let cfg = (app && app.siteInfo) || config;
  if (action && action === 'auth/session/openid') {
    cfg = config;
  }
  let url = `${cfg.siteroot}?i=${cfg.uniacid}&t=${cfg.multiid}&v=${cfg.version}&from=wxapp&m=${module || cfg.module}&divisionid=${cfg.divisionid}&`;
  if (wx.systemInfo.environment === 'wxwork') {
    url += 'env=wxwork&';
  } else {
    url += 'env=wxapp&';
  }
  if (cfg.cfgtime) {
    url += 'cfgtime=' + cfg.cfgtime + '&';
  }
  if (action) {
    action = action.split('/');
    if (action[0]) {
      url += 'c=' + action[0] + '&';
    }
    if (action[1]) {
      url += 'a=' + action[1] + '&';
    }
    if (action[2]) {
      url += 'do=' + action[2] + '&';
    }
    if (action[3]) {
      url += 'op=' + action[3] + '&';
    }
  }
  if (querystring && typeof querystring === 'object') {
    for (let param in querystring) {
      if (param && querystring.hasOwnProperty(param) && querystring[param]) {
        url += param + '=' + querystring[param] + '&';
      }
    }
  }
  return url;
};

util.geturl = function (option) {
  // let _ = require('underscore.js');
  let md5 = require('md5.js');
  // let app = getApp();
  option = option ? option : {};
  option.showLoading = typeof option.showLoading !== 'undefined' ? option.showLoading : true;

  let sessionid = wx.getStorageSync('userInfo').sessionid;
  let url = option.url;
  if (url.indexOf('http://') === -1 && url.indexOf('https://') === -1) {
    url = util.url(url);
  }
  let state = getUrlParam(url, 'state');
  if (!state && !(option.data && option.data.state) && sessionid) {
    url = url + '&state=v8uuid-' + sessionid;
  }
  // if (!option.data || !option.data.m) {
  //   let nowPage = getCurrentPages();

  //   if (nowPage.length) {
  //     nowPage = nowPage[getCurrentPages().length - 1];
  //     if (nowPage && nowPage.__route__) {
  //       url = url + '&m=' + nowPage.__route__.split('/')[0];
  //     }
  //   }
  // }

  let sign = getSign(url, option.data);
  if (sign) {
    url = url + '&sign=' + sign;
  }
  if (!url) {
    return false;
  }
  wx.showNavigationBarLoading();
  if (option.showLoading) {
    util.showLoading();
  }
  if (option.cachetime) {
    let cachekey = md5(url);
    let cachedata = wx.getStorageSync(cachekey);
    let timestamp = Date.parse(new Date());

    if (cachedata && cachedata.data) {
      if (cachedata.expire > timestamp) {
        if (option.complete && typeof option.complete === 'function') {
          option.complete(cachedata);
        }
        if (option.success && typeof option.success === 'function') {
          option.success(cachedata);
        }
        wx.hideLoading();
        wx.hideNavigationBarLoading();
        return true;
      } else {
        wx.removeStorageSync(cachekey);
      }
    }
  }
  wx.hideLoading();
  return url;
};

function getQuery(url) {
  let theRequest = [];
  if (url.indexOf('?') != -1) {
    let str = url.split('?')[1];
    let strs = str.split('&');
    for (let i = 0; i < strs.length; i++) {
      if (strs[i].split('=')[0] && unescape(strs[i].split('=')[1])) {
        theRequest[i] = {
          name: strs[i].split('=')[0],
          value: unescape(strs[i].split('=')[1]),
        };
      }
    }
  }
  return theRequest;
}
/*
* 获取链接某个参数
* url 链接地址
* name 参数名称
*/
function getUrlParam(url, name) {
  let reg = new RegExp('(^|&)' + name + '=([^&]*)(&|$)'); // 构造一个含有目标参数的正则表达式对象
  let r = url.split('?')[1].match(reg); // 匹配目标参数
  if (r != null) return unescape(r[2]);
  return null; // 返回参数值
}
/**
 * 获取签名 将链接地址的所有参数按字母排序后拼接加上token进行md5
 * url 链接地址
 * date 参数{参数名1 : 值1, 参数名2 : 值2} *
 * token 签名token 非必须
 */
function getSign(url, data, token) {
  let _ = require('underscore.js');
  let md5 = require('md5.js');
  let querystring = '';
  let sign = getUrlParam(url, 'sign');
  if (sign || (data && data.sign)) {
    return false;
  } else {
    if (url) {
      querystring = getQuery(url);
    }
    if (data) {
      let theRequest = [];
      for (let param in data) {
        if (param && data[param]) {
          theRequest = theRequest.concat({
            name: param,
            value: data[param],
          });
        }
      }
      querystring = querystring.concat(theRequest);
    }
    // 排序
    querystring = _.sortBy(querystring, 'name');
    // 去重
    querystring = _.uniq(querystring, true, 'name');
    let urlData = '';
    for (let i = 0; i < querystring.length; i++) {
      if (querystring[i] && querystring[i].name && querystring[i].value && querystring[i].value !== '0') {
        urlData += querystring[i].name + '=' + querystring[i].value;
        if (i <= querystring.length - 1) {
          urlData += '&';
        }
      }
    }
    // app取值优先，fixed by roy
    token = token ? token : ((getApp() && getApp().siteInfo.token) || config.token);
    sign = md5(urlData + token);
    return sign;
  }
}
/**
  简单封装wx.request函数，增加交互体全、配置缓存、以及配合后端格式化返回数据

  @params option 弹出参数表，
  {
    url : 同微信,
    data : 同微信,
    header : 同微信,
    method : 同微信,
    success : 同微信,
    fail : 同微信,
    complete : 同微信,
    cachetime : 缓存周期，在此周期内不重复请求http，默认不缓存
    module: 模块名，对应url中的m参数
  }
*/
util.request = function (option) {
  function cb(type, data) {
    type === 'complete' && option.complete && typeof option.complete === 'function' && option.complete(data);
    type === 'success' && option.success && typeof option.success === 'function' && option.success(data);
    type === 'fail' && option.fail && typeof option.fail === 'function' && option.fail(data);
	}

  let app = getApp();
  console.log('get app under util request');
  let md5 = require('md5.js');
  let url;
  let sign;
  let cachekey;
  let timestamp;
  let sessionid = wx.getStorageSync('userInfo').sessionid;

  option = option || {};
  option.cachetime = Number(option.cachetime) || 0;
  url = option.url;

  if (url.indexOf('http://') === -1 && url.indexOf('https://') === -1) {
    url = util.url(url, {}, option.module);
  }
  let state = getUrlParam(url, 'state');
	if (!state && !(option.data && option.data.state) && sessionid) {
		url = url + '&state=v8uuid-' + sessionid;
	}
  // m参数的获取方式已过时，在ws_common下也有页面。 m参数已在上面统一获取

  sign = getSign(url, option.method !== 'POST' ? option.data : false);
	if (sign) {
		url = url + '&sign=' + sign;
	}

	if (!url) {
		return false;
	}
	// wx.showNavigationBarLoading();
  option.showLoading && util.showLoading();

	if (option.cachetime) {
    cachekey = app.modules + md5(url);
    timestamp = Date.parse(new Date());
    let cachedata = wx.getStorageSync(cachekey);

    if (cachedata.data && cachedata.expire > timestamp) {
      cb('success', cachedata);
      cb('complete', cachedata);
				wx.hideLoading();
				wx.hideNavigationBarLoading();
				return true;
			} else {
				wx.removeStorageSync(cachekey);
			}
		}
	wx.request({
		url: url,
    data: option.data || {},
    header: option.header || {
      'content-type': 'application/x-www-form-urlencoded',
		},
    method: option.method || 'GET',
		success: function (response) {
			wx.hideNavigationBarLoading();
			wx.hideLoading();
      let errno = Number(response.data.errno || 0);

      switch (errno) {
        case 41009:
          wx.setStorageSync('userInfo', '');
          if (app.modules === 'ws_zbkq') {
            app.ws_zbkquserlogin(function() {
              util.request(option);
            });
          } else if (['ws_card', 'ws_micro_card', 'ws_hotel', 'ws_group_aide'].indexOf(app.modules) >= 0) {
            util.getUserInfo(function () {
              util.request(option);
            });
          } else {
            util._wxLogin().then((res) => {
              util.request(option);
            });
          }
          break;
        case 0:
        case 1: // TODO, 原有逻辑1和0的表现一致，需要再次检查确认
          cb('success', response);
          // 写入缓存，减少HTTP请求，并且如果网络异常可以读取缓存数据
          if (option.cachetime) {
            let cachedata = { data: response.data, expire: timestamp + option.cachetime * 1000 };
            wx.setStorageSync(cachekey, cachedata);
          }
          break;
        default:
          if (option.fail && typeof option.fail === 'function') {
            option.fail(response);
          } else {
            if (response.data.message) {
              let redirect = '';
              if (response.data.data != null && response.data.data.redirect) {
                redirect = response.data.data.redirect;
              }
              app.util.message(response.data.message, redirect, 'error');
            }
          }
          break;
      }
    },
    fail: function (response) {
      wx.hideNavigationBarLoading();
      wx.hideLoading();

      // 如果请求失败，尝试从缓存中读取数据
      cachekey = app.modules + md5(url);
      let cachedata = wx.getStorageSync(cachekey);
      if (cachedata && cachedata.data) cb('success', cachedata);
      else cb('fail', response);
    },
    complete: function (response) {
      cb('complete', response);
    },
  });
};

// 图片上传的公共方法
util.upload = function (option, callback) {
  let url = 'utility/file/upload';
  if (url.indexOf('http://') === -1 && url.indexOf('https://') === -1) {
    url = util.url(url, { type: 'audio', word: option.word, duration: option.duration });
  }
  // let responsePath = {};
  let tempFilePaths = option.filePath;
  wx.uploadFile({
    url: url,
    filePath: tempFilePaths,
    name: 'file',
    method: 'POST',
    header: {
      'Content-Type': 'multipart/form-data',
    },
    success: function (result) {
      callback && typeof callback === 'function' && callback(result);
      // if (!isJSON(result.data)) {
      // } else {
      // }
    },
  });
};
/*
* 获取用户信息
*/
// 本接口的
util.getUserInfo = function (cb, even) {
  // let openSetting = function () {
  //   wx.openSetting({
  //     success: function (res) {
  //       if (res.authSetting['scope.userInfo'] === true) {
  //         wx.showLoading({
  //           title: '自动登录中',
  //           mask: true,
  //         });
  //         login();
  //       } else {
  //         wx.hideLoading();
  //       }
  //     },
  //     fail: function () { },
  //   });
  // };
  let login = function () {
    let userInfo = {
      sessionid: '',
      wxInfo: '',
      memberInfo: '',
    };
    wx.login({
      success: function (res) {
        util.request({
          url: 'auth/session/openid',
          data: { code: res.code },
          cachetime: 0,
          success: function (session) {
            // app onlaunch 登录已经处理
            // if (session.data.data && session.data.data.isopenqywx && util.isWxWork()) {
            //   util.qyWXLogin();
            // }
            if (!session.data.errno) {
              userInfo.sessionid = session.data.data.sessionid;
              wx.setStorageSync('userInfo', userInfo);
              userInfo.wxInfo = even.userInfo;
              userInfo.wxInfo.openid = session.data.data.openid;
              wx.setStorageSync('userInfo', userInfo);
              util.request({
                url: 'auth/session/userinfo',
                data: {
                  signature: even.signature,
                  rawData: even.rawData,
                  iv: even.iv,
                  encryptedData: even.encryptedData,
                },
                method: 'POST',
                header: {
                  'content-type': 'application/x-www-form-urlencoded',
                },
                cachetime: 0,
                success: function (res) {
                  if (!res.data.errno) {
                    userInfo.memberInfo = res.data.data;
                    wx.setStorageSync('userInfo', userInfo);
                  }
                  typeof cb === 'function' && cb(userInfo);
                },
              });
            }
          },
        });
      },
      fail: function () {
        wx.showModal({
          title: '获取信息失败',
          content: '请允许授权以便为您提供给服务',
          success: function (res) {
            if (res.confirm) {
              util.getUserInfo();
            }
          },
        });
      },
    });
  };
  let app = wx.getStorageSync('userInfo');

  if (app.sessionid) {
    wx.checkSession({
      success: function () {
        typeof cb === 'function' && cb(app);
      },
      fail: function () {
        app.sessionid = '';
        wx.removeStorageSync('userInfo');
        login();
      },
    });
    if (!app.wxInfo || !app.memberInfo) {
      login();
    }
  } else {
    // 调用登录接口
    login();
  }
};
// 传递两个参数；
// params1: _this 传递当前调用这个方法的页面的实例this
// params2:boolean 是否在当前页面调用弹框；
// params3:cb 一个回调
util.access_token = function (_this, bl, cb) {
  // 获取sessitionid并存储起来；
  let login = function () {
    let userInfo = {
      sessionid: '',
      wxInfo: {},
      memberInfo: {},
    };
    wx.login({
      success: function (res) {
        util.request({
          url: 'auth/session/openid',
          data: { code: res.code },
          cachetime: 0,
          success: function (session) {
            // if (session.data.data && session.data.data.isopenqywx && util.isWxWork()) {
            //   util.qyWXLogin();
            // }
            if (!session.data.errno) {
              userInfo.sessionid = session.data.data.sessionid;
              userInfo.wxInfo.openid = session.data.data.openid;
              wx.setStorageSync('userInfo', userInfo);
              typeof cb === 'function' && cb(userInfo);
            }
          },
        });
      },
      fail: function () {
        wx.showModal({
          title: '获取信息失败',
          content: '请允许授权以便为您提供给服务',
          success: function (res) {
            if (res.confirm) {
              login();
            }
          },
        });
      },
    });
  };
  // 获取用户信息;
  let UserInfo = function () {
    wx.getUserInfo({
      success: function (wxInfo) {
        userInfo.wxInfo = wxInfo.userInfo;
        wx.setStorageSync('userInfo', userInfo);
        util.request({
          url: 'auth/session/userinfo',
          data: {
            signature: wxInfo.signature,
            rawData: wxInfo.rawData,
            iv: wxInfo.iv,
            encryptedData: wxInfo.encryptedData,
          },
          method: 'POST',
          header: {
            'content-type': 'application/x-www-form-urlencoded',
          },
          cachetime: 0,
          success: function (res) {
            if (!res.data.errno) {
              userInfo.memberInfo = res.data.data;
              wx.setStorageSync('userInfo', userInfo);
              // 重新加载当前页面;
              typeof cb === 'function' && cb(userInfo);
            }
          },
        });
      },
      fail: function () {
        wx.showModal({
          title: '授权提醒',
          content: '为更好的提供服务，需要您为我们授权部分功能，保证软件运行友好。',
          showCancel: false,
          success(res) {
            if (res.confirm) {
              UserInfo();
            }
          },
        });
      },
      complete: function () {
        // TODO
      },
    });
  };
  let userInfo = wx.getStorageSync('userInfo');
  if (userInfo.sessionid) {
    // 存在，校验是否过期；
    wx.checkSession({
      success: function () {
        // do nothing
      },
      fail: function () {
        userInfo.sessionid = '';
        wx.setStorageSync('userInfo', userInfo);
        login();
      },
    });
  } else {
    // 不存在，重新去进行获取；
    login();
  }
  if (bl) {
    UserInfo();
  }
};

util.navigateBack = function (obj) {
  let delta = obj.delta ? obj.delta : 1;
  if (obj.data) {
    let pages = getCurrentPages();
    let curPage = pages[pages.length - (delta + 1)];
    if (curPage.pageForResult) {
      curPage.pageForResult(obj.data);
    } else {
      curPage.setData(obj.data);
    }
  }
  wx.navigateBack({
    delta: delta, // 回退前 delta(默认为1) 页面
    success: function (res) {
      // success
      typeof obj.success === 'function' && obj.success(res);
    },
    fail: function (err) {
      // fail
      typeof obj.fail === 'function' && obj.function(err);
    },
    complete: function () {
      // complete
      typeof obj.complete === 'function' && obj.complete();
    },
  });
};

/*
   * 提示信息
   * type 为 success, error 当为 success,  时，为toast方式，否则为模态框的方式
   * redirect 为提示后的跳转地址, 跳转的时候可以加上 协议名称
   * navigate:/wshoto/pages/detail/detail 以 navigateTo 的方法跳转，
   * redirect:/wshoto/pages/detail/detail 以 redirectTo 的方式跳转，默认为 redirect
  */
util.message = function (title, redirect, type) {
  let url = '';
  let redirectFunction = '';
  if (!title) {
    return true;
  }
  if (typeof title === 'object') {
    redirect = title.redirect;
    type = title.type;
    title = title.title;
  }
  if (redirect) {
    let redirectType = redirect.substring(0, 9);
    if (redirectType == 'navigate:') {
      redirectFunction = 'navigateTo';
      url = redirect.substring(9);
    } else if (redirectType == 'redirect:') {
      redirectFunction = 'redirectTo';
      url = redirect.substring(9);
    } else {
      url = redirect;
      redirectFunction = 'redirectTo';
    }
  }

  if (!type) {
    type = 'success';
  }

  if (type == 'success') {
    wx.showToast({
      title: title,
      icon: 'success',
      duration: 2000,
      mask: url ? true : false,
      complete: function () {
        if (url) {
          setTimeout(function () {
            wx[redirectFunction]({
              url: url,
            });
          }, 1800);
        }
      },
    });
  } else if (type == 'error') {
    wx.showModal({
      title: '系统信息',
      content: title,
      showCancel: false,
      complete: function () {
        if (url) {
          wx[redirectFunction]({
            url: url,
          });
        }
      },
    });
  }
};

util.user = util.getUserInfo;

// 封装微信等待提示，防止ajax过多时，show多次
util.showLoading = function () {
  let isShowLoading = wx.getStorageSync('isShowLoading');
  if (isShowLoading) {
    wx.hideLoading();
    wx.setStorageSync('isShowLoading', false);
  }

  wx.showLoading({
    title: '加载中',
    complete: function () {
      wx.setStorageSync('isShowLoading', true);
    },
    fail: function () {
      wx.setStorageSync('isShowLoading', false);
    },
  });
};

util.showImage = function (event) {
  let url = event ? event.currentTarget.dataset.preview : '';
  if (!url) {
    return false;
  }
  wx.previewImage({
    urls: [url],
  });
};

/**
 * 转换内容中的emoji表情为 unicode 码点，在Php中使用utf8_bytes来转换输出
*/
util.parseContent = function (string) {
  if (!string) {
    return string;
  }

  let ranges = [
    '\ud83c[\udf00-\udfff]', // U+1F300 to U+1F3FF
    '\ud83d[\udc00-\ude4f]', // U+1F400 to U+1F64F
    '\ud83d[\ude80-\udeff]', // U+1F680 to U+1F6FF
  ];
  let emoji = string.match(new RegExp(ranges.join('|'), 'g'));

  if (emoji) {
    for (let i in emoji) {
      string = string.replace(emoji[i], '[U+' + emoji[i].codePointAt(0).toString(16).toUpperCase() + ']');
    }
  }
  return string;
};
/**
 * 时间戳转 yyy-mm-dd
 */
util.format = function (time, fmt) {
  time = time instanceof Date ? time : new Date(time);
  let o = {
    'M+': time.getMonth() + 1, // 月份
    'd+': time.getDate(), // 日
    'h+': time.getHours(), // 小时
    'm+': time.getMinutes(), // 分
    's+': time.getSeconds(), // 秒
    'q+': Math.floor((time.getMonth() + 3) / 3), // 季度
    S: time.getMilliseconds(), // 毫秒
  };
  if (/(y+)/.test(fmt)) {
    fmt = fmt.replace(RegExp.$1, (String(time.getFullYear())).substr(4 - RegExp.$1.length));
  }
  for (let k in o) {
    if (new RegExp('(' + k + ')').test(fmt)) {
      fmt = fmt.replace(RegExp.$1, RegExp.$1.length === 1 ? o[k] : ('00' + o[k]).substr((String(o[k])).length));
    }
  }
  return fmt;
};

util.formateDateTime = function (isTime) {
  let date = new Date(isTime * 1000);
  let y = date.getFullYear();
  let m = date.getMonth() + 1;
  m = m < 10 ? `0${m}` : m;
  let d = date.getDate();
  d = d < 10 ? `0${d}` : d;
  return `${y}-${m}-${d}`;
};
util.formatTime = function (isTime) {
  let date = new Date(isTime * 1000);
  let y = date.getFullYear();
  let M = date.getMonth() + 1;
  M = M < 10 ? `0${M}` : M;
  let d = date.getDate();
  d = d < 10 ? `0${d}` : d;
  let h = date.getHours();
  h = h < 10 ? `0${h}` : h;
  let m = date.getMinutes();
  m = m < 10 ? `0${m}` : m;
  let s = date.getSeconds();
  s = s < 10 ? `0${s}` : s;
  return `${y}-${M}-${d} ${h}:${m}:${s}`;
};
util.date = function () {
  /**
   * 判断闰年
   * @param date Date日期对象
   * @return boolean true 或false
   */
  this.isLeapYear = function (date) {
    return date.getYear() % 4 == 0 && (date.getYear() % 100 != 0 || date.getYear() % 400 == 0);
  };

  /**
   * 日期对象转换为指定格式的字符串
   * @param f 日期格式,格式定义如下 yyyy-MM-dd HH:mm:ss
   * @param date Date日期对象, 如果缺省，则为当前时间
   *
   * YYYY/yyyy/YY/yy 表示年份
   * MM/M 月份
   * W/w 星期
   * dd/DD/d/D 日期
   * hh/HH/h/H 时间
   * mm/m 分钟
   * ss/SS/s/S 秒
   * @return string 指定格式的时间字符串
   */
  this.dateToStr = function (formatStr, date) {
    formatStr = arguments[0] || 'yyyy-MM-dd HH:mm:ss';
    date = arguments[1] || new Date();
    let str = formatStr;
    let Week = ['日', '一', '二', '三', '四', '五', '六'];
    str = str.replace(/yyyy|YYYY/, date.getFullYear());
    str = str.replace(
      /yy|YY/,
      date.getYear() % 100 > 9 ? (date.getYear() % 100).toString() : '0' + date.getYear() % 100
    );
    str = str.replace(/MM/, date.getMonth() >= 9 ? date.getMonth() + 1 : '0' + (date.getMonth() + 1));
    str = str.replace(/M/g, date.getMonth());
    str = str.replace(/w|W/g, Week[date.getDay()]);

    str = str.replace(/dd|DD/, date.getDate() > 9 ? date.getDate().toString() : '0' + date.getDate());
    str = str.replace(/d|D/g, date.getDate());

    str = str.replace(/hh|HH/, date.getHours() > 9 ? date.getHours().toString() : '0' + date.getHours());
    str = str.replace(/h|H/g, date.getHours());
    str = str.replace(/mm/, date.getMinutes() > 9 ? date.getMinutes().toString() : '0' + date.getMinutes());
    str = str.replace(/m/g, date.getMinutes());

    str = str.replace(/ss|SS/, date.getSeconds() > 9 ? date.getSeconds().toString() : '0' + date.getSeconds());
    str = str.replace(/s|S/g, date.getSeconds());

    return str;
  };

  /**
  * 日期计算
  * @param strInterval string  可选值 y 年 m月 d日 w星期 ww周 h时 n分 s秒
  * @param num int
  * @param date Date 日期对象
  * @return Date 返回日期对象
  */
  this.dateAdd = function (strInterval, num, date) {
    date = arguments[2] || new Date();
    switch (strInterval) {
      case 's':
        return new Date(date.getTime() + 1000 * num);
      case 'n':
        return new Date(date.getTime() + 60000 * num);
      case 'h':
        return new Date(date.getTime() + 3600000 * num);
      case 'd':
        return new Date(date.getTime() + 86400000 * num);
      case 'w':
        return new Date(date.getTime() + 86400000 * 7 * num);
      case 'm':
        return new Date(
          date.getFullYear(),
          date.getMonth() + num,
          date.getDate(),
          date.getHours(),
          date.getMinutes(),
          date.getSeconds()
        );
      case 'y':
        return new Date(
          date.getFullYear() + num,
          date.getMonth(),
          date.getDate(),
          date.getHours(),
          date.getMinutes(),
          date.getSeconds()
        );
    }
  };

  /**
  * 比较日期差 dtEnd 格式为日期型或者有效日期格式字符串
  * @param strInterval string  可选值 y 年 m月 d日 w星期 ww周 h时 n分 s秒
  * @param dtStart Date  可选值 y 年 m月 d日 w星期 ww周 h时 n分 s秒
  * @param dtEnd Date  可选值 y 年 m月 d日 w星期 ww周 h时 n分 s秒
  */
  this.dateDiff = function (strInterval, dtStart, dtEnd) {
    switch (strInterval) {
      case 's':
        return parseInt((dtEnd - dtStart) / 1000);
      case 'n':
        return parseInt((dtEnd - dtStart) / 60000);
      case 'h':
        return parseInt((dtEnd - dtStart) / 3600000);
      case 'd':
        return parseInt((dtEnd - dtStart) / 86400000);
      case 'w':
        return parseInt((dtEnd - dtStart) / (86400000 * 7));
      case 'm':
        return (dtEnd.getMonth() + 1 + (dtEnd.getFullYear() - dtStart.getFullYear()) * 12 - (dtStart.getMonth() + 1));
      case 'y':
        return dtEnd.getFullYear() - dtStart.getFullYear();
    }
  };

  /**
  * 字符串转换为日期对象
  * @param date Date 格式为yyyy-MM-dd HH:mm:ss，必须按年月日时分秒的顺序，中间分隔符不限制
  */
  this.strToDate = function (dateStr) {
    let data = dateStr;
    let reCat = /(\d{1,4})/gm;
    let t = data.match(reCat);
    t[1] = t[1] - 1;
    // eval('var d = new Date(' + t.join(',') + ');');
    let d = new Date(t.join(','));
    return d;
  };

  /**
   * 时间戳转 yyy-mm-dd
   */
  this.formateDateTimea = function (isTime) {
    let date = new Date(isTime * 1000);
    let y = date.getFullYear();
    let M = date.getMonth() + 1;
    M = M < 10 ? `0${M}` : M;
    let d = date.getDate();
    d = d < 10 ? `0${d}` : d;
    let h = date.getHours();
    h = h < 10 ? `0${h}` : h;
    let m = date.getMinutes();
    m = m < 10 ? `0${m}` : m;
    let s = date.getSeconds();
    s = s < 10 ? `0${s}` : s;
    return `${y}-${M}-${d} ${h}:${m}:${s}`;
  };

  /**
  * 把指定格式的字符串转换为日期对象yyyy-MM-dd HH:mm:ss
  *
  */
  this.strFormatToDate = function (formatStr, dateStr) {
    let year = 0;
    let start = -1;
    let len = dateStr.length;
    if ((start = formatStr.indexOf('yyyy')) > -1 && start < len) {
      year = dateStr.substr(start, 4);
    }
    let month = 0;
    if ((start = formatStr.indexOf('MM')) > -1 && start < len) {
      month = parseInt(dateStr.substr(start, 2)) - 1;
    }
    let day = 0;
    if ((start = formatStr.indexOf('dd')) > -1 && start < len) {
      day = parseInt(dateStr.substr(start, 2));
    }
    let hour = 0;
    if (((start = formatStr.indexOf('HH')) > -1 || (start = formatStr.indexOf('hh')) > 1) && start < len) {
      hour = parseInt(dateStr.substr(start, 2));
    }
    let minute = 0;
    if ((start = formatStr.indexOf('mm')) > -1 && start < len) {
      minute = dateStr.substr(start, 2);
    }
    let second = 0;
    if ((start = formatStr.indexOf('ss')) > -1 && start < len) {
      second = dateStr.substr(start, 2);
    }
    return new Date(year, month, day, hour, minute, second);
  };

  /**
  * 日期对象转换为毫秒数
  */
  this.dateToLong = function (date) {
    return date.getTime();
  };

  /**
  * 毫秒转换为日期对象
  * @param dateVal number 日期的毫秒数
  */
  this.longToDate = function (dateVal) {
    return new Date(dateVal);
  };
  // 时间戳转化为指定的日期
  this.gottime = function (number, format) {
    let formateArr = ['Y', 'M', 'D', 'h', 'm', 's'];
    let returnArr = [];

    let date = new Date(number * 1000);
    returnArr.push(date.getFullYear());
    returnArr.push(key(date.getMonth() + 1));
    returnArr.push(key(date.getDate()));
    returnArr.push(key(date.getHours()));
    returnArr.push(key(date.getMinutes()));
    returnArr.push(key(date.getSeconds()));

    for (let i in returnArr) {
      if (returnArr.hasOwnProperty(i)) {
      format = format.replace(formateArr[i], returnArr[i]);
    }
    }
    return format;
  };

  /**
  * 判断字符串是否为日期格式
  * @param str string 字符串
  * @param formatStr string 日期格式， 如下 yyyy-MM-dd
  */
  this.isDate = function (str, formatStr) {
    if (formatStr == null) {
      formatStr = 'yyyyMMdd';
    }
    let yIndex = formatStr.indexOf('yyyy');
    if (yIndex === -1) {
      return false;
    }
    let year = str.substring(yIndex, yIndex + 4);
    let mIndex = formatStr.indexOf('MM');
    if (mIndex === -1) {
      return false;
    }
    let month = str.substring(mIndex, mIndex + 2);
    let dIndex = formatStr.indexOf('dd');
    if (dIndex === -1) {
      return false;
    }
    let day = str.substring(dIndex, dIndex + 2);
    if (!isNumber(year) || year > '2100' || year < '1900') {
      return false;
    }
    if (!isNumber(month) || month > '12' || month < '01') {
      return false;
    }
    if (day > getMaxDay(year, month) || day < '01') {
      return false;
    }
    return true;
  };

  this.getMaxDay = function (year, month) {
    if (month == 4 || month == 6 || month == 9 || month == 11) return '30';
    if (month == 2) {
      if ((year % 4 == 0 && year % 100 != 0) || year % 400 == 0) return '29';
      else return '28';
    }
    return '31';
  };
  /**
  * 变量是否为数字
  */
  this.isNumber = function (str) {
    let regExp = /^\d+$/g;
    return regExp.test(str);
  };

  /**
  * 把日期分割成数组 [年、月、日、时、分、秒]
  */
  this.toArray = function (myDate) {
    myDate = arguments[0] || new Date();
    let myArray = [];
    myArray[0] = myDate.getFullYear();
    myArray[1] = myDate.getMonth();
    myArray[2] = myDate.getDate();
    myArray[3] = myDate.getHours();
    myArray[4] = myDate.getMinutes();
    myArray[5] = myDate.getSeconds();
    return myArray;
  };

  /**
  * 取得日期数据信息
  * 参数 interval 表示数据类型
  * y 年 M月 d日 w星期 ww周 h时 n分 s秒
  */
  this.datePart = function (interval, myDate) {
    myDate = arguments[1] || new Date();
    let partStr = '';
    let Week = ['日', '一', '二', '三', '四', '五', '六'];
    switch (interval) {
      case 'y':
        partStr = myDate.getFullYear();
        break;
      case 'M':
        partStr = myDate.getMonth() + 1;
        break;
      case 'd':
        partStr = myDate.getDate();
        break;
      case 'w':
        partStr = Week[myDate.getDay()];
        break;
      case 'ww':
        partStr = myDate.WeekNumOfYear();
        break;
      case 'h':
        partStr = myDate.getHours();
        break;
      case 'm':
        partStr = myDate.getMinutes();
        break;
      case 's':
        partStr = myDate.getSeconds();
        break;
    }
    return partStr;
  };

  /**
  * 取得当前日期所在月的最大天数
  */
  this.maxDayOfDate = function (date) {
    date = arguments[0] || new Date();
    date.setDate(1);
    date.setMonth(date.getMonth() + 1);
    let time = date.getTime() - 24 * 60 * 60 * 1000;
    let newDate = new Date(time);
    return newDate.getDate();
  };
  return this;
};
// -------------------------------------------------------------------------------------
function key(n) {
  n = n.toString();
  return n[1] ? n : '0' + n;
}

/**
 * 统一fenxiang
 */
util.shareAppMessage = function (res) {
  let title = '统一自定义title';
  let path = '/page/index/index';
  // let imageUrl = '';
  if (res.from === 'button') {
    // 来自页面内转发按钮
  }
  return {
    title,
    path,
    // imageUrl,
    success: function (res) {
      // 转发成功
    },
    fail: function (res) {
      // 转发失败
    },
  };
};

/**
 * @param pageUrl String 必填，页面绝对路径，不带参数
 * @param urlParams Object 页面参数，键值对
 * @param close Boolean/String 跳转方式，true：关闭当前页再跳转；'all'：关闭所有页面再跳转
 */
util.navigateTo = function (pageUrl, urlParams, close) {
  const app = getApp();
  const objParams = {};
  let tabBars = [];
  let tabBarPages = [];
  let currentModuleIndex = app.tabbarindex;// 当前选择模块 Number
  let isVirtual = (config.tabbar_type || app.siteInfo.tabbar_type) === '2'; // 主模块是否为虚拟菜单 Boolean
  if (app && app.tabInfo && app.tabInfo[currentModuleIndex] && app.tabInfo[currentModuleIndex].tabBar) {
    const tabbar = app.tabInfo[currentModuleIndex].tabBar;
    tabBars = isVirtual ? (tabbar.v_list || tabbar.list) : tabbar.list;
    tabBars.forEach((item) => tabBarPages.push(item.pagePath));
  }
  pageUrl = pageUrl.substr(0, 1) === '/' ? pageUrl.substr(1) : pageUrl;
  let isTabbarPage = tabBarPages.indexOf(pageUrl) !== -1;
  // 原生菜单跳转参数处理 by wangjuan 2019/5/23
   if (isTabbarPage && !isVirtual){
    app.globalSwitchTabParam = urlParams;
    urlParams = {};
  }
  let strParams = '';
  for (const key in urlParams) {
    if (!urlParams.hasOwnProperty(key)) {
      continue;
    }
    // 对参数做编码，所以如果参数值包含中文，取用时要解码
    strParams += `${key}=${encodeURIComponent(urlParams[key])}&`;
  }
  strParams = strParams.replace(/&$/, '');

  objParams.url = `/${pageUrl}${strParams ? `?${strParams}` : ''}`;

  // tabbar页面只能通过reLaunch实现关闭当前页
  // 修改内容：在原来的基础之上添加两种情况，1.均为虚拟tabbar，增加变量isVirtual，true时均为虚拟tabbar 2.辅模块页面跳转到该模块自身tabbar页面的时候,
  // 以现在的判定条件直接会导向switchttab导致跳转失败；所以增加了tabbarindex！==0 代表是辅模块的tabbar；
  if (close === 'all' || (isTabbarPage && (close || isVirtual || currentModuleIndex !== 0))) {
    wx.reLaunch(objParams);
  } else if (isTabbarPage && !isVirtual) {
    wx.switchTab(objParams);
  } else if (close) {
    wx.redirectTo(objParams);
  } else {
    wx.navigateTo(objParams);
  }
};

// 微信登录 2018/5/3
util._wxLogin = function () {
  return new Promise((resolve, reject) => {
    function login() {
      let userInfo = { sessionid: '', openid: '' };
      const systemInfo = wx.getSystemInfoSync();
      wx.login({
        success: (res) => {
          util.request({
            url: 'auth/session/openid',
            data: {
              code: res.code,
              brand: systemInfo.brand,
              model: systemInfo.model,
            },
            cachetime: 0,
            success: (session) => {
              // APPonlaunch登录已处理
              // if (session.data.data && session.data.data.isopenqywx && util.isWxWork()) {
              //   util.qyWXLogin();
              // }
              userInfo.sessionid = session.data.data.sessionid;
              userInfo.openid = session.data.data.openid;
              wx.setStorageSync('userInfo', userInfo);
              resolve(session);
            },
            fail: (res) => {
              reject(res);
            },
          });
        },
      });
    }

    let userInfo = wx.getStorageSync('userInfo') || '';
    if (userInfo.sessionid && userInfo.openid) {
      // 存在，校验是否过期；
      wx.checkSession({
        success: () => {
          resolve(userInfo);
        },
        fail: () => {
          wx.removeStorageSync('userInfo');
          login();
        },
      });
    } else {
      // 不存在，重新去进行获取；
      login();
    }
  });
};

// 获取用户信息 2018-5-15
util._authUserInfo = function () {
  return new Promise((resolve, reject) => {
    wx.getSetting({
      success: (res) => {
        if (res.authSetting['scope.userInfo']) {
          wx.getUserInfo({
            success: res => {
              let { signature, rawData, iv, encryptedData, userInfo } = res;
              util.request({
                url: 'auth/session/userinfo',
                data: { signature, rawData, iv, encryptedData },
                method: 'POST',
                header: {
                  'content-type': 'application/x-www-form-urlencoded',
                },
                cachetime: 0,
                success: (res) => {
                  let { uid } = res.data.data;
                  userInfo.uid = uid;
                  wx.setStorageSync('_wxInfo', userInfo);
                  resolve(userInfo);
                },
              });
            },
          });
        } else {
          reject(res);
        }
      },
    });
  });
};

// fenxiang连接添加当前小程序的切换项中排第几这个参数；
// params e ：share的title、path、imageUrl
// params page 当前fenxiang的页面实例
util.shareInformation = function (e, page) {
  let app = getApp();
  if (e.path) {
    e.path = (e.path.indexOf('?') !== -1) ? e.path + '&tabbarindex=' + app.tabbarindex : e.path + '?tabbarindex=' + app.tabbarindex;
  } else {
    e.path = page.route + '?tabbarindex=' + app.tabbarindex;
  }
  return e;
};

// tabbarindex 接收当前小程序的切换项中排第几这个参数；
util.receiveParameter = function (opt) {
  let app = getApp();
  app.tabbarindex = opt.tabbarindex ? opt.tabbarindex : app.tabbarindex;
};

// 客服会话session_from值的获取2018/5/23
util.getSessionFormStr = function (str) {
  let obj = {};
  if (str) {
    let response = mbStringLength(str);
    if (response.cut) {
      obj.nickName = str.substring(0, response.curr);
    } else {
      obj.nickName = str;
    }
  } else {
    obj.nickName = '';
  }
  return JSON.stringify(obj);
};

function mbStringLength(s) {
  let totalLength = 0;
  let i;
  let curr = 0;
  let charCode;
  let cut;
  for (i = 0; i < s.length; i++) {
    if (s.charAt(i).match(/[^\x00-\xff]/ig) != null) {
      charCode = s.charCodeAt(i);
      if (charCode < 0x007f) {
        totalLength += 1;
      } else if ((0x0080 <= charCode) && (charCode <= 0x07ff)) {
        totalLength += 2;
      } else if ((0x0800 <= charCode) && (charCode <= 0xffff)) {
        totalLength += 3;
      } else if ((0x10000 <= charCode) && (charCode <= 0x10ffff)) {
        totalLength += 4;
      }
    } else {
      totalLength += 1;
    }
    if (totalLength <= 17) {
      curr += 1;
      cut = false;
    } else {
      cut = true;
    }
  }
  return { curr, cut };
}

/**
 * 电话号码正则表达式
 */
util.phoneExp = {
  // mobile: /^(13[0-9]|14[579]|15[0-3,5-9]|16[6]|17[0135678]|18[0-9]|19[89])\d{8}$/,
  mobile: /^(13[0-9]|14[579]|15[0-3,5-9]|16[6]|17[0135678]|18[0-9]|19[0-9])\d{8}$/,
  canadaPhone: /^(\+?1)?[2-9]\d{2}[2-9](?!11)\d{6}$/,
  landline: /^[0|4|8]\d{2,3}(-?)[0-9]\d{6,8}$/,
};

// 返回后台未关闭的模块列表和当前选中的模块；
util.getCurrentTabInfo = function () {
  let app = getApp();
  let pagePath = getCurrentPages()[0].route;
  let result = new Promise((resolve, reject) => {
    util.request({
      url: 'auth/session/aliasShow',
      cachetime: 0,
      success: function (res) {
        resolve(res);
      },
      fail: function (err) {
        reject(err);
      },
    });
  });
  return result.then(function (res) {
    let showModule = [];
    // 更改模块名称；===朱志阳
    if (res.errMsg === 'request:ok' && res.data && res.data.data) {
      // 获取到单个模块开关的数组，通过遍历过滤掉被关闭的模块剩余；剩余是用来做展示的模块；
      res.data.data.forEach((item, index) => {
        if (JSON.parse(item).status !== 0) {
          app.siteInfo.appJson[index].name = JSON.parse(item).title;
          showModule.push(app.siteInfo.appJson[index]);
        }
      });
    }
    return showModule;
  }).then(function (showModule) {
    let selected = 0;// 默认当前选中模块为第一个；
    app.tabInfo = showModule;// 保存剩余模块的数组；
    if (showModule.length > 1) { // 判断剩余模块数量如果小于1，就不让组件显示；
      let moduleName = pagePath.substr(0, pagePath.indexOf('/')) || '';// 根据页面路径获得模块名称；
      showModule.forEach((item, index) => { // 遍历过滤后的数组，根据模块名称对比每一项，确定当前选中模块所在位置，返回位置的序号;
        if (item.module === moduleName) { selected = index; app.tabbarindex = index }
      });
    }
    let params = { showModule, selected };
    return params;// 将最终开启状态的模块和当前选中项序号返回；
  });
};

/**
 * debug开关
 * @returns {number} 0 or 1  (0:关闭,1:开启)
 */
util.switchDebug = () => {
  // 放在app onshow生命周期里判断
  // let app = getApp();
  // if (app.modules === 'ws_micro_shop') return false;
  const login = () => {
    return new Promise((resolve, reject) => {
      wx.login({
        success: (res) => {
          util.request({
            url: 'auth/session/openid',
            data: {
              code: res.code,
            },
            cachetime: 0,
            success: res => {
              resolve(res.data.data.openid);
            },
            fail: res => {
              reject(res);
            },
          });
        },
      });
    });
  };
  const state = (openid) => {
    util.request({
      url: 'auth/session/copyright',
      data: {
        openid,
      },
      success: res => {
        let { debug: enableDebug = 0, debug_wxapp = 0 } = res.data.data;
        if (!debug_wxapp) { return }
        if (enableDebug === 0 || enableDebug === '0' || enableDebug === 1 || enableDebug === '1') {
          wx.setEnableDebug({
            enableDebug: !!enableDebug,
          });
          console.log(`debug设置成功 当前状态: ${!!enableDebug}`);
        }
      },
      faile: err => {
        console.log('debug设置失败', err);
      },
    });
  };
  login().then(openid => {
    state(openid);
  });
};

// 分享时加入share_scene和openid   liupl 2018/09/25
util.spliceSharePath = function(path, share_scene, moduleName) {
  let openid = '';

  if (moduleName === 'ws_micro_shop') {
    openid = wx.getStorageSync('OPENID');
    if (path.indexOf('?') === -1) {
      path += '?openid=' + openid + '&share_scene=' + share_scene;
    } else {
      path += '&openid=' + openid + '&share_scene=' + share_scene;
    }
    return path;
  } else if (moduleName === 'ws_diancan_multi') {
    openid = wx.getStorageSync('openid');
    if (!openid) {
      openid = wx.getStorageSync('userInfo') && wx.getStorageSync('userInfo').openid;
    }
    if (path.indexOf('?') === -1) {
      path += '?openid=' + openid + '&share_scene=' + share_scene;
    } else {
      path += '&openid=' + openid + '&share_scene=' + share_scene;
    }
    return path;
  } else {
    openid = wx.getStorageSync('userInfo') && wx.getStorageSync('userInfo').openid;
    if (path.indexOf('?') === -1) {
      path += '?openid=' + openid + '&share_scene=' + share_scene;
    } else {
      path += '&openid=' + openid + '&share_scene=' + share_scene;
    }
    return path;
  }
};

// 解析options  liupl 2018/09/25
util.parseOptions = function(options) {
  const exp = /^[0-9]*$/;
  let optionsKeys = Object.keys(options);
  let scene = options && options.scene;
  if (optionsKeys.length === 0) {
    return false;
  } else if (optionsKeys.length === 1 && optionsKeys.indexOf('scene') === 0) {
    if (!exp.test(scene)) {
      let scenePair = scene && decodeURIComponent(scene).split('&');
      let sceneObj = {};
      scenePair.forEach(function (item) {
        let key = item.slice(0, item.indexOf('='));
        let value = item.slice(item.indexOf('=') + 1, item.length);
        sceneObj[key] = value;
      });
      return sceneObj;
    } else {
      return 'fenxiao';
    }
  } else {
    return options;
  }
};

// 通用的准备身份绑定数据的方法，必须在share页面的onLoad生命周期函数中调用。  liupl 2018/09/25
util.prepareBindInfo = function(options, moduleName, that) {
  let _that = that;
  let app = getApp();
  let parsedOptions = util.parseOptions(options);
  let openid = '';
  if (parsedOptions && parsedOptions === 'fenxiao') {
    return false;
  } else {
    // 获取share_scene.
    let share_scene = parsedOptions && parsedOptions.share_scene;
    _that.setData({ share_scene });

    // 获取fromOpenid, 如果是太阳码过来的，要通过uid换取openid。通用海报适用。  liupl 2018/09/25
    if (parsedOptions && parsedOptions.openid) {
      _that.setData({ fromOpenid: parsedOptions.openid });
    } else if (parsedOptions && parsedOptions.from_uid) {
      let uid = parsedOptions.from_uid;
      util.request({
        url: 'card/api/get_fans',
        data: { uid },
        success: function (res) {
          if (res.data.errno === 0) {
            let fromOpenid = res.data.data && res.data.data.openid;
            _that.setData({ fromOpenid });
          }
        },
      });
    }

    // 获取本人openid，兼容商城。
    if (moduleName === 'ws_micro_shop') {
      openid = wx.getStorageSync('OPENID');
      if (!openid) {
        app.ws_micro_shoplogin().then(() => {
          openid = wx.getStorageSync('OPENID');
          _that.setData({ localOpenid: openid });
        });
      } else {
        _that.setData({ localOpenid: openid });
      }
    } else {
      openid = wx.getStorageSync('openid');
      if (!openid) {
        util._wxLogin().then(res => {
          openid = res.openid
            ? res.openid
            : (res.data.data.openid ? res.data.data.openid : '');
          _that.setData({ localOpenid: openid });
        });
      } else {
        _that.setData({ localOpenid: openid });
      }
    }
  }

  
};

// 发送身份绑定信息数据  liupl 2018/09/25
util.sendBindInfo = function(data) {
  let { localOpenid: openid, fromOpenid: from_openid, share_scene } = data;
  if (!openid || !from_openid || !share_scene) {
    return false;
  } else {
    util.request({
      url: 'card/api/bind_from',
      data: {
        openid,
        from_openid,
        share_scene,
      },
    });
}
};

util.getMatchColor = function (color) {
  let matchColor = '';
  let themeType = 'dark';
  switch (color) {
    case '#fe7951':
      matchColor = '#ff9a7c';
      break;
    case '#6c9cff':
      matchColor = '#b3ccff';
      break;
    case '#ffa94c':
      matchColor = '#ffbb71';
      break;
    case '#fb6137':
      matchColor = '#ff7a56';
      break;
    case '#8bd05c':
      matchColor = '#9eea6a';
      break;
    case '#ff4040':
      matchColor = '#ff7373';
      break;
    case '#56c5ff':
      matchColor = '#8ed8ff';
      break;
    case '#77b54d':
      matchColor = '#9eea6a';
      break;
    case '#37bffd':
      matchColor = '#8ed8ff';
      break;
    case '#fa5e6a':
      matchColor = '#ff808a';
      break;
    case '#010101':
      matchColor = '#010101';
      break;
    default:
      matchColor = '#b3ccff';
      break;
  }

  return { themeType, matchColor };
};

util.statRequest = function (opts) {
  // TODO，后台需要解析，需要登录或者自动openID
  util.request({
    url: 'card/api/access_log',
    data: {
      pt: opts.pt,
      tm: opts.tm,
      pm: opts.pm,
      tp: opts.tp,
      cn: opts.cn,
      aa: opts.aa || '',
      card_id: opts.card_id || '', // 非必须
      is_module: opts.is_module || 0,
    },
    success: function () {
      // body...
    },
    complete: function () {
      // body...
    },
  });
};

util.statRequest2 = function (opts) {
  // TODO，后台需要解析，需要登录或者自动openID
  util.request({
    url: 'card/api/access_log2',
    data: {
      pt: opts.pt,
      tm: opts.tm,
      pm: opts.pm,
      tp: opts.tp,
      cn: opts.cn,
      aa: opts.aa || '',
      card_id: opts.card_id || '', // 非必须
      is_module: opts.is_module || 0,
    },
    success: function () {
      // body...
    },
    complete: function () {
      // body...
    },
  });
};

/*
  企业微信相关
 */

// 内部接口不暴露
// session过期自动登录
function _qyLogin(options) {
  wx.qy.login({
    success(result) {
      result.code && util.request({
        url: 'auth/workwechat/userid',
    data: {
          code: result.code,
        },
        cachetime: 0,
        showLoading: false,
        success(res) {
          options && options.success && options.success();
          // console.log('企业auth/workwechat/userid', res.data.data);
        },
      });
    },
    fail(e) {
      options && options.fail && options.fail();
    },
  });
}

util.isWxWork = function() {
  return wx.getStorageSync('isWXWork');
};

// 暴露的对外接口1。 在各wx.login() && auth/session/openid 成功之下，如果开启企业微信侧并是在企业微信环境下，紧接着进行企业微信登录，并进行厂商服务器登录（绑定userID和openID）。
util.qyWXLogin = function() {
  _qyLogin();
};

// 暴露的外部接口2，供小程序端调用企业微信专用接口时的会话状态验证
// 失败自动重新登录
util.qyWXCheckSeesion = function(options) {
  wx.qy.checkSession({
    // 微信session
    success(res) {
      // 自家服务器session
      util.request({
        url: 'auth/workwechat/checkSession',
        cachetime: 0,
        showLoading: false,
        success(session) {
          console.log('auth/workwechat/checkSession===', session.data.data.check);
          if (!session.data.data.check) {
            return _qyLogin(options);
    }
          options.success && options.success();
        },
        fail() {
          console.log('服务商企业session失效');
          _qyLogin(options);
        },
      });
    },
    fail() {
      console.log('企业微信session失效');
      _qyLogin(options);
    },
  });
};

module.exports = util;
